<template>
  <div class="app-container">
    <h1 style="margin-top:10px">音量监测初始化</h1> 
    <el-progress style="width:300px" :percentage="audioLevel" :format="format" />
  </div>
</template>
<script>
import { defineComponent, onMounted, reactive, toRefs } from 'vue'
import SoundMeter from "../../utils/soundmeter"
export default defineComponent({
  setup() {
    const state=reactive({
      audioLevel: 0
    })
    const format = (percentage) => (percentage === 100 ? 'Full' : `${percentage}%`)
    onMounted(()=>{
      try{
        window.AudioContext=window.AudioContext||window.webkitAudioContext
        window.audioContext=new AudioContext()
      }catch(e){
        console.log("网页音频API不支持")
      }
      soundMeter=window.soundMeter=new SoundMeter(window.audioContext)
      const constraints=window.constraints={
        audio:true,
        video: false
      }
      navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError)
    })
    const handleSuccess=(stream)=>{
      window.stream=stream
      soundMeter.connectToSource(stream)
      setTimeout(soundMeterProcess,100);
    }
    const soundMeterProcess=()=>{
      var val=(window.soundMeter.instant.toFixed(2)*348)+1
      state.audioLevel=val
      setTimeout(soundMeterProcess,100)
    }
    const handleError=(error)=>{
      console.log('getUserMedia error:',error.message,error.name)
    }
    return {
      ...toRefs(state),
      format
    }
  },
})
</script>
<style scoped>
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
#video {
  box-sizing: border-box;
  padding: 0 10px;
  width: 100%;
  height: 500px;
}
.btn-group {
  display: flex;
  flex-direction: row;
  margin-top: 10px;
}
</style>
